package org.example.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.example.config.JwtConfig;
import org.example.constant.CodeEnum;
import org.example.exception.ServiceException;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Component
public class GetUidUtil {

    private final JwtConfig jwtConfig;

    public GetUidUtil(JwtConfig jwtConfig) {
        this.jwtConfig = jwtConfig;
    }

    public String getUid(){
        //解析token  得到uid
        // 获取当前请求
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        // 从请求头中获取Authorization的值
        String authorizationHeader = request.getHeader("Authorization");
        if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer ")) {
//            log.warn("无效的Authorization头");
            throw new ServiceException(CodeEnum.UNAUTHORIZED);
        }
        // 获取token，去掉 "Bearer " 前缀
        String token = authorizationHeader.substring(7);
//        log.info("token为：{}", token);

        if (token.startsWith("{") && token.endsWith("}")) {
            token = token.substring(1, token.length() - 1);
        }

        Claims claims = null;
        try {
            claims = Jwts.parser()
                    .setSigningKey(jwtConfig.getJwtSecret())
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
//            log.error("解析JWT时发生错误: ", e);
            throw new ServiceException(CodeEnum.UNAUTHORIZED);
        }
        return claims.getSubject();
    }
}

